"""
服务端逻辑处理
"""
from socket import socket
from multiprocessing import Process
from db import *


class Handle(Process):
    def __init__(self,conn):
        self.conn = conn
        self.db = Data()
        self.user_id = 0
        super().__init__()

    #总分结构  总体接受请求 分情况讨论
    def run(self):
        while True:
            request = self.conn.recv(128).decode()
            data = request.split(" ")
            #分情况讨论
            if not request or data[0] == "E":
                break
            elif data[0] == "R":
                self.do_regit(data[1],data[2])
            elif data[0] == "L":
                self.do_login(data[1],data[2])
            elif data[0] == "Q":
                self.do_qury(data[1])
            elif data[0] == "H":
                self.do_hist()

        self.db.close()
        self.conn.close()

    def do_regit(self,name,password):
        if self.db.register(name,password):
            self.conn.send(b"T")
        else:
            self.conn.send(b"F")

    def do_login(self,name,password):
        res = self.db.login(name, password)
        if res:
            self.user_id = res[0]
            self.conn.send(b"T")
        else:
            self.conn.send(b"F")

    def do_qury(self,word):
        data = self.db.qury(word)
        if data:
            self.conn.send(data[0].encode())
            self.db.insert_hist(self.user_id,word)
        else:
            self.conn.send(b"F")

    def do_hist(self):
        data = self.db.hist(self.user_id)
        if data:
            res = "T\t"
            for row in data:
                res += "%s,%s,%s;"%row
            self.conn.send(res.encode())
        else:
            self.conn.send(b"F")

class Server:
    def __init__(self,host = "",port = 0):
        self.host = host
        self.port = port
        self.address = (host,port)
        self.sock = self.__get__sock()
    def __get__sock(self):
        sock = socket()
        sock.bind(self.address)
        return sock
    def main(self):
        self.sock.listen(10)
        while True:
            self.conn,self.addr = self.sock.accept()
            h = Handle(self.conn)
            h.start()

if __name__ == '__main__':
    m = Server(host="0.0.0.0", port=8864)
    m.main()

